#include "main.h"
int ListInitiate(LNode **head){
    (*head) = (LNode *) malloc(sizeof(LNode));
    if(!*head){
        return 1;
    }
    (*head)->next = NULL;
    return 0;
}

int ListLength(LNode *head){
    int length=0;
    LNode *p;
    p = head->next;
    while (p){
        length++;
        p= p->next;
    }
    return length;
}

int ListInsert(LNode *head, int i, DataType x) {
    LNode *p=head,*s;int j=0;
    while (p && j<i){
        p=p->next;
        j++;
    }
    if (!p ||j>i)return 1;
    s = (LNode*) malloc(sizeof(LNode));
    s->data = x;
    s->next = p->next;
    p->next = s;
    return 0;
}

int ListDelete(LNode *head, int i, DataType *x) {
    LNode *p = head,*q;
    int j=0;
    while ((p->next)&&(j<i)){
        p = p->next;
        j++;
    }
    if(!(p->next) ||(j>i)){
        return 1;
    }
    q = p->next;
    p->next = q->next;
    *x = q->data;
    free(q);
    return 0;
}

int ListGet(LNode *head, int i, DataType *x) {
    LNode *p;int j = 0;
    p = head->next;
    while (p&&j<i)
    {
        p = p->next;
        ++j;
    }
    if(!p || j>i){
        return 1;
    }
    *x = p->data;
    return 0;
}

int Destroy(LNode **head)
{
    LNode *p,*q;
    p = (*head)->next;
    if(*head==NULL){
        return 1;
    }
    while (p!=NULL){
        q = p->next;
        free(p);
        p=q;
    }
    (*head)->next =NULL;
    return 0;
}
void main(void) {
    LNode *head;
    int i , x;
    ListInitiate(&head);/*初始化*/
    for(i = 0; i < 10; i++) {
        if(ListInsert(head, i, i+1) == 0) /*插入10个数据元素*/
        {
            printf("错误! \n");
            return;
        }
    }
    if(ListDelete(head, 4, &x) == 0) { /*删除数据元素5*/
        printf("错误! \n");
        return;
    }
    for(i = 0; i < ListLength(head); i++) {
        if(ListGet(head, i, &x) == 0) /*取元素*/
        {
            printf("错误! \n");
            return;
        }
        else printf("%d    ", x);/*显示数据元素*/
    }
    Destroy(&head);
}